import React, { useEffect, useState, useMemo } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Cell, Divider, Image, Checkbox, Stepper, Toast, SubmitBar } from 'react-vant'
import { async_shoplist } from '../store/Slice'
import { async_updateshoplist, async_carlist } from '../store/Slice'

export default function Car() {

  let dispatch = useDispatch()
  useEffect(() => {
    dispatch(async_shoplist())
    dispatch(async_carlist())
  }, [])
  let obj = useSelector(state => state.crms1)
  //console.log(obj);

  //全选
  const isAll = obj.carlist.length > 0 && obj.carlist.every(item => {
    return item.checked
  })

  let total = useMemo(() => {
    return obj.carlist.reduce((p, n) => {
      if (n.checked) {
        return p + n.price * n.num
      }
      return p
    }, 0)
  }, [obj.carlist])



  return (
    <div>
      {/* 购物车渲染 单元格组件 */}
      <div style={{ paddingBottom: '50px' }}>
        {
          obj.carlist.map(item => {
            return <Cell
              center
              key={item.id}
              title={item.title}
              label={item.price}
              icon={<div>
                <div style={{ marginRight: '5px' }}><Checkbox checked={item.checked} onChange={() => {
                  /* 状态切换 */
                  let obj = {
                    ...item,
                    "checked": !item.checked
                  }
                  dispatch(async_updateshoplist(obj))
                }} /></div>
                <div>
                  <Image width={44} height={44} src={item.img} round />
                </div>
              </div>}
              value={<Stepper
                min={1}
                value={item.num}
                onChange={v => {
                  let obj = {
                    ...item,
                    num: v
                  }
                  dispatch(async_updateshoplist(obj))
                }}
              />}
            />
          })
        }
      </div>

      {/* 提交订单栏 */}
      <div className="demo-submit-bar">
        <SubmitBar
          price={total * 100}
          buttonText="提交订单"
        >
          <Checkbox checked={isAll} onChange={(checked) => {
            //console.log(checked);
            obj.carlist.forEach(item => {
              let obj = {
                ...item,
                checked: checked
              }
              dispatch(async_updateshoplist(obj))
            })
          }}>全选</Checkbox>
        </SubmitBar>
      </div>

    </div >
  )
}
